﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SSN.Objects;
using SSN.Utilities;
using SSN.Utilities.Security;
using SSN.Utilities.Cache;
using SSN.Utilities.Database;
using SSN.BusinessFramework;
using SSN.BusinessFramework.Forms;

namespace SSN.WebFramework
{
    public class FormManager
    {
        #region caching
        private static KeyValueCache<int, Form> _formCache = new KeyValueCache<int, Form>(_initForms, getForm, new TimeSpan(4, 0, 0));


        private static Dictionary<int, Form> _initForms()
        {
            List<Form> list = DbManager.BossDb.CreateListFromQuery<Form>(new SystemSecurityContext(), string.Format("SELECT * FROM {0}", Form.TableName));
            Dictionary<int, Form> table = new Dictionary<int, Form>();
            foreach (Form f in list)
            {
                table[f.ID] = f;
            }

            return table;
        }

        private static Form getForm(int id)
        {
            Form d = new Form();
            SystemSecurityContext ctx = new SystemSecurityContext();
            if (d.Load(ctx, id))
            {
                return d;
            }

            return null;
        }

        private SSNSecurityContext _ctx;

        public void PurgeCache()
        {
            _formCache.Purge(_ctx);
        }
        #endregion

        public FormManager(SSNSecurityContext ctx)
        {
            _ctx = ctx;
        }

        public Form GetForm(int id)
        {
            return _formCache[id];
        }

        public List<Form> GetRecentlyUpdatedForms()
        {
            return (from f in _formCache.AllValues orderby f.FormDate descending select f).Take(5).ToList();
        }
    }
}
